<%@ include file="../import_page.jsp"%>
<%@ page import="org.json.*"%>
<%
	//login checking
	if (!loginedChecking(session, UsersType.admin)) {
		//user don't login
		//redirect to home page
		response.sendRedirect(URL_HOMEPAGE);
		return;
	}

	//select unit check
	if (!selectUnitCheck(session)) {
		//if user didn't select an Unit
		//redirtect to select page
		response.sendRedirect(URL_SELECT_UNIT);
		return;
	}

	Units selectUnit = (Units) session
			.getAttribute(SESSION_SELECT_UNIT);
	String errMsg = null;

	//input check
	String unitIdStr = request.getParameter(PAR_UNIT_ID);
	if (isEmptyString(unitIdStr)
			|| !unitIdStr.equalsIgnoreCase(selectUnit.getId())) {
		//Incorrect request
		errMsg = "incorrect unit selected input: "+ unitIdStr+ " Selected: "+ selectUnit.getId();
	}

	String listUserStr = request.getParameter(PAR_NAMES_LIST);
	if (isEmptyString(listUserStr)) {
		//Incorrect request
		errMsg = "incorrect name list input name_list: "+ listUserStr;
	}
	
	if (isEmptyString(errMsg)) {
		try {
			JSONArray jArr = new JSONArray(listUserStr);
			int length = jArr.length();
			String[] listUser = new String[length];
			for (int i = 0; i < length; i++) {
				listUser[i] = jArr.getString(i);
			}

			UnitsControl uCon = new UnitsControl();
			uCon.updateUserInUnit(selectUnit.getId(), listUser);
			uCon.closeDBConnection();

		} catch (Exception err) {
			errMsg = err.toString();
		}
	}

	//response setting
	response.setContentType("text/json");

	//print json string
	JSONObject jObj = new JSONObject();
	boolean isError = !isEmptyString(errMsg);
	jObj.put("isError", isError);
	if (isError)
		jObj.put("Msg",  errMsg);
	else
		jObj.put("Msg", "Update Complete");

	out.print(jObj.toString());
%>